package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.common.aliyun.OSSService;
import com.usian.common.dtos.PageResult;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.threadlocal.UserThreadLocalUtils;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.wemedia.entity.WmMaterial;
import com.usian.wemedia.entity.WmNewsMaterial;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.wemedia.service.IWmNewsMaterialService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-07-07
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {

    @Autowired
    private OSSService ossService;

    @Override
    public String uploadPic(MultipartFile file) {
        //参数校验
        if (file == null) {
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID, "上传文件不能为空");
        }
        //获取线程中保存得用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        if (userId == null) {
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //调用上传工具类，完成oss完成文件上传
        try {
            String url = ossService.upload(file);
            //保存素材数据
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(userId);
            wmMaterial.setCreatedTime(new Date());
            wmMaterial.setIsCollection(false);
            wmMaterial.setType(0);
            wmMaterial.setUrl(url);
            save(wmMaterial);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR, "文件上传失败");
        }
    }

    @Override
    public PageResult<WmMaterial> findByPage(WmMaterialDto dto) {
        if (dto == null) {
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //获取用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        if (userId == null) {
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //设置分页参数
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        //设置是否收藏得查询条件
        QueryWrapper<WmMaterial> queryWrapper = new QueryWrapper<>();
        String isCollection = dto.getIsCollection();
        Boolean isBooColl = null;
        if (isCollection != null) {
            if (isCollection.equals("1")) {
                isBooColl = true;
                queryWrapper.lambda().eq(WmMaterial::getIsCollection, isBooColl);
            }
        }
        queryWrapper.lambda().eq(WmMaterial::getUserId, userId);
        //设置根据创建时间排序
        queryWrapper.lambda().orderByDesc(WmMaterial::getCreatedTime);
        //执行查询
        IPage<WmMaterial> iPage = page(page, queryWrapper);

        PageResult<WmMaterial> pageResult = new PageResult<>(dto.getPage(), dto.getSize(), iPage.getTotal(), iPage.getRecords());
        return pageResult;
    }

    @Override
    public void updateCollect(Integer id, boolean isCollection) {
            if (id==null){
                throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
            }

            //获取用户id
        Integer userId = UserThreadLocalUtils.getUserId();
            if (userId==null){
                throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
            }
        //更新收藏状态
        UpdateWrapper<WmMaterial> updateWrapper=new UpdateWrapper<>();
            updateWrapper.lambda().eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,userId).set(WmMaterial::getIsCollection,isCollection);

        boolean b = update(updateWrapper);
        if (!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Autowired
    private IWmNewsMaterialService wmNewsMaterialService;

    @Override
    public void delPicture(Integer id) {
        if (id==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //获取用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        if (userId==null){
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //判断素材是否被使用
        QueryWrapper<WmNewsMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WmNewsMaterial::getMaterialId,id);
        List<WmNewsMaterial> list = wmNewsMaterialService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)){
            throw new LeadException(AppHttpCodeEnum.DATA_EXIST,"素材数据已经被使用，不能删除");
        }

        //删除素材
        QueryWrapper<WmMaterial> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,userId);
        boolean b = remove(queryWrapper1);
        if (!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
